<template>
</template>

<script setup>
import {FeatureService, GetFeaturesBySQLParameters,
  SurfaceAnalystParametersSetting,GeometrySurfaceAnalystParameters,SpatialAnalystService } from "@supermap/iclient-ol";
import Point from 'ol/geom/Point';
import { iServerHttp } from "@/map/projMap.js";
import Polygon from 'ol/geom/Polygon';
import Feature from 'ol/Feature';
import { WKT } from "ol/format";
import GeoJSON from 'ol/format/GeoJSON';
import { savePolygonEvaluateResult,softSoilPointToGridPolygon } from "@/api/weakSoilAssess/indexAssess";
import { getDetails,saveSandPolygonEvaluateResult } from "@/api/sandliquidAssess/indexAssess1";


const { proxy } = getCurrentInstance();
const props = defineProps(['open','weakSoilAssessList','sandliquidAssessList','taskId']);
const emits = defineEmits(['close']);
const openCount = ref(false);//是否开启空间分析

const data = reactive({
  /*queryParams: {
    //裁剪区域--任务区域
    clipUrl:"http://10.13.155.192:8090/iserver/services/data-fxfzdzzh/rest/data",
    clipDatasource:"fxfzdzzh",//数据源
    clipDataset:"dzzh_task",//数据集
    clipSql:"dt_id='cf4678069c524036943f284ef7bea925'",//裁剪区域SQL语句
    //点数据集url
    url:"http://10.13.155.192:8090/iserver/services/data-fxfzdzzh/rest/data",
    datasource:"fxfzdzzh",//数据源
    dataset:"dzzh_soft_soil_evaluate_result",//数据集
    sql:"dtcv_id='509a51ad4e4e42d9941927d5ddb3test'",//点数据集SQL语句
    //空间分析url
    spatialUrl:"http://10.13.155.192:8090/iserver/services/spatialAnalysis-fxfzdzzh/restjsr/spatialanalyst",
  },*/
  weakSoilAssessResult: {//根据是否软土震陷点数据生成等值面
    count:0,
    list:[]
  },
  sandliquidAssessResult: {//根据是否砂土液化点数据生成等值面
    count:0,
    list:[]
  }
})
const { weakSoilAssessResult,sandliquidAssessResult } = toRefs(data);

//面转wkt
function polygonToWKT(polygon) {
  console.log(polygon);
  let polygonWkt = new WKT().writeGeometry(polygon);
  console.log("polygonWkt");
  console.log(polygonWkt);
  return polygonWkt;
}

//根据是否软土震陷点数据生成等值面
function weakSoilAssess(){
  if(openCount.value){
    let list = props.weakSoilAssessList;
    weakSoilAssessResult.value.count = 0;
    weakSoilAssessResult.value.list = [];
    if(list && list.length>0){
      // weakSoilAssessIsoregion(list,"7");
      // weakSoilAssessIsoregion(list,"8");
      // weakSoilAssessIsoregion(list,"9");
      let dtId = props.taskId;
      let dtcvId = list[0].dtcvId;
      //软土震陷点数据克吕金插值分析提取等值面发布
      weakSoilPointToGridPolygon(dtId,dtcvId);
    }
  }
}

//软土震陷点数据克吕金插值分析提取等值面发布
function weakSoilPointToGridPolygon(dtId,dtcvId){
  softSoilPointToGridPolygon({dtId:dtId,dtcvId:dtcvId}).then((response) => {
    console.log(response);
    proxy.$modal.alert("等值面计算成功");
    handleClose();
  }).catch(() => {
    proxy.$modal.alert("等值面计算失败");
    handleClose();
  });
}

//根据是否软土震陷点数据生成等值面
function weakSoilAssessIsoregion(list,type) {
  //空间分析url
  let spatialUrl = iServerHttp() + "/iserver/services/spatialAnalysis-fxfzdzzh/restjsr/spatialanalyst";
  //获取点数据
  if (list && list.length>0) {
    let points = [];//点坐标信息数组(y,x)
    let zValues = [];//z值数组
    //获取服务器返回的结果
    console.log(type+"--获取点数据");
    console.log(list);
    for (let i = 0; i < list.length; i++) {
      let properties = list[i];
      points[i] = new Point([properties.longitude,properties.latitude]);
      if(type=="7"){
        zValues[i] = Number(properties.isSoft7=="是"?1:0);
      }else if(type=="8"){
        zValues[i] = Number(properties.isSoft8=="是"?1:0);
      }else if(type=="9"){
        zValues[i] = Number(properties.isSoft9=="是"?1:0);
      }
    }
    console.log(points);
    console.log(zValues);
    ///提取等值面
    //表面分析参数设置
    let extractParams = new SurfaceAnalystParametersSetting({
      datumValue: 0, // 表面分析中提取等值线基准值
      interval: 0.5, // 等值距，两条等值线之间的间隔值
      resampleTolerance: 0, // 重采样容限。获取或设置重采样容限。 容限值越大，采样结果数据越简化。当分析结果出现交叉时，可通过调整重采样容限为较小的值来处理。
      smoothMethod: "BSPLINE", // 光滑处理所使用的方法
      smoothness: 0, // 等值线的光滑度。获取或设置表面分析中等值线或等值面的边界线的光滑度。 以为 0-5 为例，光滑度为 0 表示不进行光滑操作，值越大表示光滑度越高。 随着光滑度的增加，提取的等值线越光滑，当然光滑度越大， 计算所需的时间和占用的内存也就越大。而且，当等值距较小时， 光滑度太高会出现等值线相交的问题。
      clipRegion: null // 裁剪对象(********xy坐标一定要记得反转**************)
    });
    //表面分析提取操作参数
    let surfaceAnalystParams = new GeometrySurfaceAnalystParameters({
      points: points,
      zValues: zValues,
      extractParameter: extractParams,
      resolution: 0.0001,//设置指定中间结果（栅格数据集）的分辨率
      surfaceAnalystMethod: "ISOREGION"  //设置提取等值线ISOLINE/等值面ISOREGION
    });
    let resultArray = [];//结果数组
    //点数据生成等值面数据
    new SpatialAnalystService(spatialUrl).surfaceAnalysis(surfaceAnalystParams, (serviceResult2) => {
      console.log(type+"--点数据生成等值面数据");
      console.log(serviceResult2);
      if(serviceResult2.type=="processCompleted"){
        //等值线添加到图层中
        let fea_result = serviceResult2.result.recordset.features.features
        for (let f = 0; f<fea_result.length; f++){
          // let dMinZValue = fea_result[f].properties.dminzvalue;
          let dMaxZValue = fea_result[f].properties.dmaxzvalue;
          //面转wkt
          let geom = polygonToWKT((new GeoJSON()).readGeometry(JSON.stringify(fea_result[f].geometry)));
          //服务器返回的是coord需要转成latLng
          let value = 0;
          if(Number(dMaxZValue)<=0.5){//小于0.5的等值面
            value = 0;
          }else{//大于0.5的等值面
            value = 1;
          }
          resultArray.push({dtcvId:list[0].dtcvId,value:value,geom:geom,type:type});
        }
        console.log(type+"--结果数组长度--"+resultArray.length);
        console.log(resultArray);
        weakSoilAssessResult.value.count = weakSoilAssessResult.value.count + 1;
        weakSoilAssessResult.value.list = weakSoilAssessResult.value.list.concat(resultArray);
        if(weakSoilAssessResult.value.count==3){
          console.log("保存是否软土震陷生成等值面的计算结果");
          console.log(weakSoilAssessResult.value);
          if(weakSoilAssessResult.value.list.length>0){
            savePolygonEvaluateResult(weakSoilAssessResult.value.list).then((response) => {
              console.log(response);
              // proxy.$modal.msgSuccess(response.message);
              proxy.$modal.alert("评估成功");
              handleClose();
            }).catch(() => {
              proxy.$modal.alert("保存失败");
              handleClose();
            });
          }else{
            proxy.$modal.alert("无等值面评估结果");
            handleClose();
          }
        }
      }else{//失败
        console.log(type+"--结果数组长度--"+resultArray.length);
        console.log(resultArray);
        weakSoilAssessResult.value.count = weakSoilAssessResult.value.count + 1;
        weakSoilAssessResult.value.list = weakSoilAssessResult.value.list.concat(resultArray);
        if(weakSoilAssessResult.value.count==3){
          console.log("保存是否软土震陷生成等值面的计算结果");
          console.log(weakSoilAssessResult.value);
          if(weakSoilAssessResult.value.list.length>0){
            savePolygonEvaluateResult(weakSoilAssessResult.value.list).then((response) => {
              console.log(response);
              // proxy.$modal.msgSuccess(response.message);
              proxy.$modal.alert("评估成功");
              handleClose();
            }).catch(() => {
              proxy.$modal.alert("保存失败");
              handleClose();
            });
          }else{
            proxy.$modal.alert("无等值面评估结果");
            handleClose();
          }
        }
      }
    });
  }
}

/*//根据点数据生成等值面
function isoregion() {
  // let paramsObj = queryParams.value;
  let datasource = "fxfzdzzh";
  //空间分析url
  let spatialUrl = "http://10.13.155.192:8090/iserver/services/spatialAnalysis-fxfzdzzh/restjsr/spatialanalyst";
  //点数据集url
  let url = "http://10.13.155.192:8090/iserver/services/data-fxfzdzzh/rest/data";
  //裁剪区域--任务区域
  let clipUrl = "http://10.13.155.192:8090/iserver/services/data-fxfzdzzh/rest/data";
  let clipDatasource = "fxfzdzzh";
  let clipDataset = "dzzh_task";
  let taskId = "cf4678069c524036943f284ef7bea925";
  let clipSql = "dt_id='"+taskId+"'";
  //获取任务Region
  let sqlParam = new GetFeaturesBySQLParameters({
    queryParameter: {
      name: clipDataset,
      attributeFilter: clipSql
    },
    datasetNames: [clipDatasource+":"+clipDataset],
    toIndex: 1  //返回1条数据
  });
  new FeatureService(clipUrl).getFeaturesBySQL(sqlParam, function (serviceResult0) {
    // 获取服务器返回的结果
    console.log("获取裁剪区域");
    console.log(serviceResult0);
    let pointGroup = [];
    let fea0 = serviceResult0.result.features.features;
    for(let u = 0; u<serviceResult0.result.featureCount; u++){
      let coordinates00 = fea0[u].geometry.coordinates[0][0]
      pointGroup[u] = [];
      for (let b = 0; b<coordinates00.length; b++){
        pointGroup[u].push([coordinates00[b][1], coordinates00[b][0]]);//经纬度反转
      }
    }
    console.log(pointGroup);
    // return
    let clipRegion = new Feature({
      geometry: new Polygon(pointGroup)
    });
    console.log(clipRegion);

    //获取点数据
    if (pointGroup.length>0) {
      let points = []  //点坐标信息数组(y,x)
      let zValues = []  //z值数组
      //获取软土震陷点数据
      let dataset = "dzzh_soft_soil_evaluate_result";
      let dtcvId = "509a51ad4e4e42d9941927d5ddb3test";
      let sql = "dtcv_id='" + dtcvId + "'"  //SQL语句
      let sqlParam = new GetFeaturesBySQLParameters({
        queryParameter: {
          name: dataset,
          attributeFilter: sql
        },
        datasetNames: [datasource+":"+dataset],
        toIndex: -1  //返回至多1000条数据（在没有修改IServer文件的前提下）
      })
      new FeatureService(url).getFeaturesBySQL(sqlParam, (serviceResult) => {
        //获取服务器返回的结果
        console.log("获取点数据");
        console.log(serviceResult);
        let features = serviceResult.result.features
        for (let i = 0; i < features.features.length; i++) {
          let properties = features.features[i].properties
          // points[i] = {"y":properties.LONGITUDE, "x":properties.LATITUDE};
          points[i] = new Point([properties.LONGITUDE,properties.LATITUDE]);
          zValues[i] = Number(properties.IS_SOFT7);
        }
        console.log(points);
        console.log(zValues);
        ///提取等值面
        //表面分析参数设置
        let extractParams = new SurfaceAnalystParametersSetting({
          datumValue: 0, // 表面分析中提取等值线基准值
          interval: 0.5, // 等值距，两条等值线之间的间隔值
          resampleTolerance: 0, // 重采样容限
          smoothMethod: "BSPLINE", // 光滑处理所使用的方法
          smoothness: 3, // 等值线的光滑度
          clipRegion: null // 裁剪对象(********xy坐标一定要记得反转**************)
        });
        //表面分析提取操作参数
        let surfaceAnalystParams = new GeometrySurfaceAnalystParameters({
          points: points,
          zValues: zValues,
          extractParameter: extractParams,
          resolution: 0.01,
          surfaceAnalystMethod: "ISOREGION"  //设置提取等值线ISOLINE/等值面ISOREGION
        });
        let resultArray = [];//结果数组
        //点数据生成等值面数据
        new SpatialAnalystService(spatialUrl).surfaceAnalysis(surfaceAnalystParams, (serviceResult2) => {
          console.log("点数据生成等值面数据");
          console.log(serviceResult2);
          //等值线添加到图层中
          let fea_result = serviceResult2.result.recordset.features.features
          for (let f = 0; f<fea_result.length; f++){
            // let dMinZValue = fea_result[f].properties.dMinZValue;
            let dMaxZValue = fea_result[f].properties.dMaxZValue;
            //面转wkt
            let geom = polygonToWKT((new GeoJSON()).readGeometry(JSON.stringify(fea_result[f].geometry)));
            //服务器返回的是coord需要转成latLng
            if(dMaxZValue=="0.5"){//小于0.5的等值面
              resultArray.push({value:0,geom:geom});
            }else{//大于0.5的等值面
              resultArray.push({value:1,geom:geom});
            }
          }
          console.log("结果数组");
          console.log(resultArray);
        })
      })
    }
  })
}*/

//根据是否砂土液化点数据生成等值面
function sandliquidAssess(){
  if(openCount.value){
    console.log("根据是否砂土液化点数据生成等值面");
    let resultList = props.sandliquidAssessList;
    console.log(resultList);
    if(resultList){
      let type = resultList.type;//1:标贯法；2：液化指数法；3：层次分析法
      let list = resultList.list;//DzzhResultSandLiquefaction
      sandliquidAssessResult.value.count = 0;
      sandliquidAssessResult.value.list = [];
      if(list && list.length>0){
        console.log("length--"+list.length);
        let dmslId = resultList.dmslId;//模型ID
        for(let i=0;i<list.length;i++){
          let earthquakeAcceleration = list[i].earthquakeAcceleration;//地震动加速度
          let groundWaterDepth = list[i].liquefactionGroundWaterDepth;//地下水位深度（液化判别地下水位深度dw(m)）
          let canShow = list[i].canShow;//是否展示评估结果-地图查看结果处的查看按钮 1：可以；0：不可以
          if(canShow=="1"){
            let count = list.length;
            console.log(i+"--listlength--"+count);
            //获取砂土液化点数据列表生成等值面
            getSandliquidPointList(dmslId,earthquakeAcceleration,groundWaterDepth,count,type);
          }else{
            let count = list.length;
            sandliquidAssessResult.value.count = sandliquidAssessResult.value.count + 1;
            console.log("count"+sandliquidAssessResult.value.count);
            //完成砂土液化生成等值面
            completeSandliquidAssessResult(count);
          }
        }
      }
    }
  }
}

//获取砂土液化点数据列表生成等值面
function getSandliquidPointList(dmslId,earthquakeAcceleration,groundWaterDepth,count,type) {
  getDetails({
    "dmslId": dmslId,
    "earthquakeAcceleration": earthquakeAcceleration,
    "liquefactionGroundWaterDepth": groundWaterDepth,
  }).then(response => {
    console.log(response.data)
    let list = response.data;//DzzhResultDetailSandLiquefaction
    //根据是否砂土液化点数据生成等值面
    sandliquidAssessIsoregion(list,dmslId,earthquakeAcceleration,groundWaterDepth,count,type);
  });
}

//根据是否砂土液化点数据生成等值面
function sandliquidAssessIsoregion(list,dmslId,earthquakeAcceleration,groundWaterDepth,count,type) {
  //空间分析url
  let spatialUrl = iServerHttp() + "/iserver/services/spatialAnalysis-fxfzdzzh/restjsr/spatialanalyst";
  //获取点数据
  if (list && list.length>0) {
    let tempLonLatArray = [];
    let points = [];//点坐标信息数组(y,x)
    let zValues = [];//z值数组
    //获取服务器返回的结果
    console.log("dmslId--"+dmslId+",earthquakeAcceleration--"+earthquakeAcceleration+",groundWaterDepth--"+groundWaterDepth+"--获取点数据");
    console.log(list);
    for (let i = 0; i < list.length; i++) {
      let properties = list[i];
      // points[i] = new Point([properties.longitude,properties.latitude]);
      let tempLonLat = [properties.longitude,properties.latitude];
      let bool = true;
      if(tempLonLatArray.length>0){
        for(let j=0;j<tempLonLatArray.length;j++){
          if(tempLonLatArray[j][0]==tempLonLat[0] && tempLonLatArray[j][1]==tempLonLat[1]){
            bool = false;
            break;
          }
        }
      }else{
        console.log("tempLonLat");
      }
      if(bool){
        console.log(tempLonLat);
        tempLonLatArray.push(tempLonLat);
        let point = new Point(tempLonLat);
        points.push(point);
      }else{
        continue;
      }
      let zValue = 0;
      if(type=="1"){
        zValue = Number(properties.drillLiquefactionDifferentiate=="液化"?1:0);
      }else if(type=="2"){
        zValue = properties.dei;//钻孔液化指数 0不液化 (0,6]轻微 (6,18]中等 >18严重
        /*zValue = 0;//不液化
        if(properties.sandLevel=="轻微"){
          zValue = 1;
        }else if(properties.sandLevel=="中等"){
          zValue = 2;
        }else if(properties.sandLevel=="严重"){
          zValue = 3;
        }*/
      }else if(type=="3"){
        zValue = 0;//test
      }
      // zValues[i] = zValue;
      zValues.push(zValue);
    }
    console.log(points);
    console.log(zValues);
    let datumValue = 0;// 表面分析中提取等值线基准值
    let interval = 0.5;// 等值距，两条等值线之间的间隔值
    if(type=="1"){//标贯法
      datumValue = 0;// 表面分析中提取等值线基准值
      interval = 0.5;// 等值距，两条等值线之间的间隔值
    }else if(type=="2"){//液化指数法
      /*datumValue = 0;// 表面分析中提取等值线基准值
      interval = 0.5;// 等值距，两条等值线之间的间隔值*/
      datumValue = 0;// 表面分析中提取等值线基准值
      interval = 3;// 等值距，两条等值线之间的间隔值
    }else if(type=="3"){//层次分析法
      //
    }
    ///提取等值面
    //表面分析参数设置
    let extractParams = new SurfaceAnalystParametersSetting({
      datumValue: datumValue, // 表面分析中提取等值线基准值
      interval: interval, // 等值距，两条等值线之间的间隔值
      resampleTolerance: 0, // 重采样容限。获取或设置重采样容限。 容限值越大，采样结果数据越简化。当分析结果出现交叉时，可通过调整重采样容限为较小的值来处理。
      smoothMethod: "BSPLINE", // 光滑处理所使用的方法
      smoothness: 0, // 等值线的光滑度。获取或设置表面分析中等值线或等值面的边界线的光滑度。 以为 0-5 为例，光滑度为 0 表示不进行光滑操作，值越大表示光滑度越高。 随着光滑度的增加，提取的等值线越光滑，当然光滑度越大， 计算所需的时间和占用的内存也就越大。而且，当等值距较小时， 光滑度太高会出现等值线相交的问题。
      clipRegion: null // 裁剪对象(********xy坐标一定要记得反转**************)
    });
    //表面分析提取操作参数
    let surfaceAnalystParams = new GeometrySurfaceAnalystParameters({
      points: points,
      zValues: zValues,
      extractParameter: extractParams,
      resolution: 0.001,//设置指定中间结果（栅格数据集）的分辨率
      surfaceAnalystMethod: "ISOREGION"  //设置提取等值线ISOLINE/等值面ISOREGION
    });
    let resultArray = [];//结果数组
    //点数据生成等值面数据
    new SpatialAnalystService(spatialUrl).surfaceAnalysis(surfaceAnalystParams, (serviceResult2) => {
      console.log("点数据生成等值面数据");
      console.log(serviceResult2);
      if(serviceResult2.type=="processCompleted"){
        //等值线添加到图层中
        let fea_result = serviceResult2.result.recordset.features.features
        for (let f = 0; f<fea_result.length; f++){
          // let dMinZValue = fea_result[f].properties.dminzvalue;
          let dMaxZValue = fea_result[f].properties.dmaxzvalue;
          //面转wkt
          let geom = polygonToWKT((new GeoJSON()).readGeometry(JSON.stringify(fea_result[f].geometry)));
          //服务器返回的是coord需要转成latLng
          let value = 0;
          if(type=="1"){//标贯法
            if(Number(dMaxZValue)<=0.5){//小于0.5的等值面
              value = 0;//不液化
            }else{//大于0.5的等值面
              value = 1;//液化
            }
          }else if(type=="2"){//液化指数法
            /*if(Number(dMaxZValue)<=0.5){//小于0.5的等值面
              value = 0;//不液化
            }else if(Number(dMaxZValue)<=1.5){//小于1.5的等值面
              value = 1;//轻微
            }else if(Number(dMaxZValue)<=2.5){//小于2.5的等值面
              value = 2;//中等
            }else{//大于2.5的等值面
              value = 3;//严重
            }*/
            //钻孔液化指数 0不液化 (0,6]轻微 (6,18]中等 >18严重
            if(Number(dMaxZValue)==0){//0不液化
              value = 0;//不液化
            }else if(Number(dMaxZValue)<=6){//(0,6]轻微
              value = 1;//轻微
            }else if(Number(dMaxZValue)<=18){//(6,18]中等
              value = 2;//中等
            }else{//>18严重
              value = 3;//严重
            }
          }else if(type=="3"){//层次分析法
            //
          }
          resultArray.push({value:value,geom:geom,dmslId:dmslId,earthquakeAcceleration:earthquakeAcceleration,groundWaterDepth:groundWaterDepth,algorithmType:type});
        }
        console.log("结果数组长度--"+resultArray.length);
        console.log(resultArray);
        sandliquidAssessResult.value.count = sandliquidAssessResult.value.count + 1;
        sandliquidAssessResult.value.list = sandliquidAssessResult.value.list.concat(resultArray);
        console.log("count"+sandliquidAssessResult.value.count);
        if(sandliquidAssessResult.value.count==count){
          //完成砂土液化生成等值面
          completeSandliquidAssessResult(count);
        }
      }else{//失败
        console.log("结果数组长度--"+resultArray.length);
        console.log(resultArray);
        sandliquidAssessResult.value.count = sandliquidAssessResult.value.count + 1;
        sandliquidAssessResult.value.list = sandliquidAssessResult.value.list.concat(resultArray);
        console.log("count"+sandliquidAssessResult.value.count);
        if(sandliquidAssessResult.value.count==count){
          //完成砂土液化生成等值面
          completeSandliquidAssessResult(count);
        }
      }
    });
  }else{
    handleClose();
  }
}

//完成砂土液化生成等值面
function completeSandliquidAssessResult(count){
  if(sandliquidAssessResult.value.count==count){
    console.log("保存是否砂土液化生成等值面的计算结果");
    console.log(sandliquidAssessResult.value);
    if(sandliquidAssessResult.value.list.length>0){
      saveSandPolygonEvaluateResult(sandliquidAssessResult.value.list).then((response) => {
        console.log(response);
        // proxy.$modal.msgSuccess(response.message);
        proxy.$modal.alert("评估成功");
        handleClose();
      }).catch(() => {
        proxy.$modal.alert("保存失败");
        handleClose();
      });
    }else{
      proxy.$modal.alert("无等值面评估结果");
      handleClose();
    }
  }
}

function handleClose(){
  openCount.value = false//是否开启空间分析
  emits('close', true);
}

//获取开启空间分析
const isOpen = watch(() => props.open, value => {// watch函数监听props.open   //根据是否软土震陷点数据生成等值面
  openCount.value = value;//是否开启空间分析
},{immediate:true});

//获取是否软土震陷点数据
const getWeakSoilAssessList = watch(() => props.weakSoilAssessList, value => {// watch函数监听props.weakSoilAssessList   //根据是否软土震陷点数据生成等值面
  weakSoilAssess();
},{immediate:true});

//获取是否砂土液化点数据
const getSandliquidAssessList = watch(() => props.sandliquidAssessList, value => {// watch函数监听props.sandliquidAssessList   //根据是否砂土液化点数据生成等值面
  sandliquidAssess();
},{immediate:true});

</script>

<style scoped lang="scss">

</style>